---
title: "Reference: createTool() | Tools | Agents | Kastrax Docs"
description: Documentation for the createTool function in Kastrax, which creates custom tools for agents and workflows.
---

# `createTool()` ✅

The `createTool()` function creates typed tools that can be executed by agents or workflows. Tools have built-in schema validation, execution context, and integration with the Kastrax ecosystem.

## Overview ✅

Tools are a fundamental building block in Kastrax that allow agents to interact with external systems, perform computations, and access data. Each tool has:

- A unique identifier
- A description that helps the AI understand when and how to use the tool
- Optional input and output schemas for validation
- An execution function that implements the tool's logic

## Example Usage ✅

```ts filename="src/tools/stock-tools.ts" showLineNumbers copy
import { createTool } from "@kastrax/core/tools";
import { z } from "zod";

// Helper function to fetch stock data
const getStockPrice = async (symbol: string) => {
  const response = await fetch(
    `https://kastrax-stock-data.vercel.app/api/stock-data?symbol=${symbol}`
  );
  const data = await response.json();
  return data.prices["4. close"];
};

// Create a tool to get stock prices
export const stockPriceTool = createTool({
  id: "getStockPrice",
  description: "Fetches the current stock price for a given ticker symbol",
  inputSchema: z.object({
    symbol: z.string().describe("The stock ticker symbol (e.g., AAPL, MSFT)")
  }),
  outputSchema: z.object({
    symbol: z.string(),
    price: z.number(),
    currency: z.string(),
    timestamp: z.string()
  }),
  execute: async ({ context }) => {
    const price = await getStockPrice(context.symbol);
    
    return {
      symbol: context.symbol,
      price: parseFloat(price),
      currency: "USD",
      timestamp: new Date().toISOString()
    };
  }
});

// Create a tool that uses the thread context
export const threadInfoTool = createTool({
  id: "getThreadInfo",
  description: "Returns information about the current conversation thread",
  inputSchema: z.object({
    includeResource: z.boolean().optional().default(false)
  }),
  execute: async ({ context, threadId, resourceId }) => {
    return {
      threadId,
      resourceId: context.includeResource ? resourceId : undefined,
      timestamp: new Date().toISOString()
    };
  }
});
```

## API Reference ✅

### Parameters

`createTool()` accepts a single object with the following properties:

<PropertiesTable
  content={[
    {
      name: "id",
      type: "string",
      required: true,
      description: "Unique identifier for the tool. This should be descriptive of the tool's function."
    },
    {
      name: "description",
      type: "string",
      required: true,
      description: "Detailed description of what the tool does, when it should be used, and what inputs it requires. This helps the AI understand how to use the tool effectively."
    },
    {
      name: "execute",
      type: "(context: ToolExecutionContext, options?: any) => Promise<any>",
      required: false,
      description: "Async function that implements the tool's logic. Receives the execution context and optional configuration.",
      properties: [
        {
          type: "ToolExecutionContext",
          parameters: [
            {
              name: "context",
              type: "object",
              description: "The validated input data that matches the inputSchema"
            },
            {
              name: "threadId",
              type: "string",
              isOptional: true,
              description: "Identifier for the conversation thread, if available"
            },
            {
              name: "resourceId",
              type: "string",
              isOptional: true,
              description: "Identifier for the user or resource interacting with the tool"
            },
            {
              name: "kastrax",
              type: "Kastrax",
              isOptional: true,
              description: "Reference to the Kastrax instance, if available"
            },
          ]
        },
        {
          type: "ToolOptions",
          parameters: [
            {
              name: "toolCallId",
              type: "string",
              description: "The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data."
            },
            {
              name: "messages",
              type: "CoreMessage[]",
              description: "Messages that were sent to the language model to initiate the response that contained the tool call. The messages do not include the system prompt nor the assistant response that contained the tool call."
            },
            {
              name: "abortSignal",
              type: "AbortSignal",
              isOptional: true,
              description: "An optional abort signal that indicates that the overall operation should be aborted."
            },
          ]
        }
      ]
    },
    {
      name: "inputSchema",
      type: "ZodSchema",
      required: false,
      description: "Zod schema that defines and validates the tool's input parameters. If not provided, the tool will accept any input."
    },
    {
      name: "outputSchema",
      type: "ZodSchema",
      required: false,
      description: "Zod schema that defines and validates the tool's output. Helps ensure the tool returns data in the expected format."
    },
  ]}
/>

### Returns

<PropertiesTable
  content={[
    {
      name: "Tool",
      type: "Tool<TSchemaIn, TSchemaOut>",
      description: "A Tool instance that can be used with agents, workflows, or directly executed.",
      properties: [
        {
          type: "Tool",
          parameters: [
            {
              name: "id",
              type: "string",
              description: "The tool's unique identifier"
            },
            {
              name: "description",
              type: "string",
              description: "Description of the tool's functionality"
            },
            {
              name: "inputSchema",
              type: "ZodSchema | undefined",
              description: "Schema for validating inputs"
            },
            {
              name: "outputSchema",
              type: "ZodSchema | undefined",
              description: "Schema for validating outputs"
            },
            {
              name: "execute",
              type: "Function",
              description: "The tool's execution function"
            }
          ]
        }
      ]
    }
  ]}
/>

## Type Safety ✅

The `createTool()` function provides full type safety through TypeScript generics:

- Input types are inferred from the `inputSchema`
- Output types are inferred from the `outputSchema`
- The execution context is properly typed based on the input schema

This ensures that your tools are type-safe throughout your application.

## Best Practices ✅

1. **Descriptive IDs**: Use clear, action-oriented IDs like `getWeatherForecast` or `searchDatabase`
2. **Detailed Descriptions**: Provide comprehensive descriptions that explain when and how to use the tool
3. **Input Validation**: Use Zod schemas to validate inputs and provide helpful error messages
4. **Error Handling**: Implement proper error handling in your execute function
5. **Idempotency**: When possible, make your tools idempotent (same input always produces same output)
6. **Performance**: Keep tools lightweight and fast to execute
